package com.alibaba.system.service.impl;



import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.system.domain.Role;
import com.alibaba.system.mapper.RoleMapper;
import com.alibaba.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    // 重构添加
    @Override
    public void add(Role role) {
        super.add(role);
        addData((role));
    }

    // 重构修改
    @Override
    public void update(Role role) {
        roleMapper.delRoleMenuByRoleId(role.getId());
        roleMapper.delRolePermissionByRoleId(role.getId());
        //再添加新的权限
        addData(role);
        super.update(role);
    }

    // 重构删除
    @Override
    public void del(Long id) {
        //删除中间表数据
        roleMapper.delRoleMenuByRoleId(id);
        roleMapper.delRolePermissionByRoleId(id);
        roleMapper.delEmployeeRoleByRoleId(id);
        super.del(id);
    }

    // 重构批量删除
    @Override
    public void atchDelete(Long[] id) {
        for (Long ids : id) {
            del(ids);
        }
    }

    // 抽取公共方法供添加和修改的时候使用
    private void addData(Role role){
        List<Long> menus = role.getMenus();
        if(menus.size()>0){
            roleMapper.addRoleMenu(role.getId(),menus);
        }
        List<Long> permissions = role.getPermissions();

        if(permissions.size()>0){
            roleMapper.addRolePermissions(role.getId(),permissions);
        }

    }
}
